package com.example.onlinereadingsystem.demos.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.onlinereadingsystem.demos.web.dto.common.BaseContext;
import com.example.onlinereadingsystem.demos.web.dto.domain.User;
import com.example.onlinereadingsystem.demos.web.dto.domain.UserFollow;
import com.example.onlinereadingsystem.demos.web.dto.request.*;
import com.example.onlinereadingsystem.demos.web.dto.vo.MyCommentVo;
import com.example.onlinereadingsystem.demos.web.dto.vo.MyFansVo;
import com.example.onlinereadingsystem.demos.web.dto.vo.MyFollowersVo;
import com.example.onlinereadingsystem.demos.web.dto.vo.UserInfoVo;
import com.example.onlinereadingsystem.demos.web.enums.OSSCommonConstant;
import com.example.onlinereadingsystem.demos.web.mapper.CommentMapper;
import com.example.onlinereadingsystem.demos.web.mapper.UserFollowMapper;
import com.example.onlinereadingsystem.demos.web.service.UserService;
import com.example.onlinereadingsystem.demos.web.mapper.UserMapper;
import com.example.onlinereadingsystem.demos.web.util.AliOSSUtils;
import com.example.onlinereadingsystem.demos.web.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author 27935
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-10-09 11:25:09
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private CommentMapper commentMapper;

    /**
     * @auther ljm
     * @create 2024/10/18
     * @describe 根据用户id获取用户详情
     */
    @Override
    public Result<UserInfoVo> getUserInfoById(String id) {
        String userId = BaseContext.getId();
        if (Strings.isEmpty(id)) {
            return Result.error("用户未登录");
        }
        User user = userMapper.selectById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        UserInfoVo res = new UserInfoVo();
        BeanUtils.copyProperties(user, res);
        UserFollow followedInfo = getFollowedInfo(userId, id, 1);
        res.setIsFollowed(followedInfo != null);
        return Result.OK(res);
    }

    /**
     * @auther ljm
     * @create 2024/12/26
     * @describe 修改用户信息
     */
    @Override
    public Result<Boolean> updateUserInfo(UpdateUserInfoParam param) {
        String id = BaseContext.getId();
        if (Strings.isEmpty(id)) {
            return Result.error("用户未登录!");
        }
        if (Strings.isEmpty(param.getUsername())) {
            return Result.error("用户名不能为空!");
        }
        param.setId(id);
        User user = userMapper.selectById(id);
        if (!user.getUsername().equals(param.getUsername())) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, param.getUsername());
            if (userMapper.selectList(queryWrapper).size() > 0) {
                return Result.error("用户名已存在");
            }
        }
        if (Strings.isNotEmpty(param.getAvatar())) {
            if (!param.getAvatar().equals(user.getAvatar())) {
                String avatar = user.getAvatar();
                if (Strings.isNotBlank(avatar)) {
                    aliOSSUtils.delete(OSSCommonConstant.AVATAR, avatar.substring(avatar.lastIndexOf("/") + 1));
                }
            }
        }
        BeanUtils.copyProperties(param, user);
        userMapper.updateById(user);
        return Result.OK(true);
    }

    /**
     * @auther ljm
     * @create 2025/1/5
     * @describe 上传头像
     */
    @Override
    public Result<String> uploadAvatar(MultipartFile file) {
        if (file == null) {
            return Result.error("上传文件为空");
        }
        String url = "";
        try {
            url = aliOSSUtils.upload(file, OSSCommonConstant.AVATAR);
        } catch (Exception e) {
            log.info("头像上传失败 userId: " + BaseContext.getId());
            return Result.error("头像上传失败");
        }
        return Result.OK(url);
    }

    /**
     * @auther ljm
     * @create 2025/1/5
     * @describe 获取我的评论
     */
    @Override
    public Result<IPage<MyCommentVo>> getMyComments(MyCommentParam param) {
        if (Strings.isEmpty(param.getUserId())) {
            return Result.error("查询失败");
        }
        Page<MyCommentVo> page = new Page<>(param.getPage(), param.getSize());
        IPage<MyCommentVo> allComments = new Page<>();
        // 获取回复
        allComments = commentMapper.getReplyComments(param, page);
        return Result.OK(allComments);
    }

    /**
     * @auther ljm
     * @create 2025/1/10
     * @describe 获取我的粉丝
     */
    @Override
    public Result<IPage<MyFansVo>> getMyFans(MyFansParam param) {
        // 当前登录用户id
        String currentUserId = BaseContext.getId();
        if (Strings.isEmpty(param.getUserId())) {
            return Result.error("用户未登录");
        }
        Page<MyFansVo> page = new Page<>(param.getPage(), param.getSize());
        IPage<MyFansVo> res = userFollowMapper.getMyFans(param, page);
        List<MyFansVo> records = res.getRecords();
        for (MyFansVo vo : records) {
            if (!Strings.isEmpty(currentUserId)) {
                UserFollow uesrFollow = userFollowMapper.isFollowed(currentUserId, vo.getUserId());
                vo.setIsFollowed(uesrFollow != null);
            } else {
                vo.setIsFollowed(false);
            }
        }
        return Result.OK(res);
    }

    /**
     * @auther ljm
     * @create 2025/1/10
     * @describe 获取我的关注
     */
    @Override
    public Result<IPage<MyFollowersVo>> getMyFollowers(MyFollowersParam param) {
        // 当前登录用户id
        String currentUserId = BaseContext.getId();
        if (Strings.isEmpty(param.getUserId())) {
            return Result.error("用户未登录");
        }
        Page<MyFollowersVo> page = new Page<>(param.getPage(), param.getSize());
        IPage<MyFollowersVo> res = userFollowMapper.getMyFollowers(param, page);
        List<MyFollowersVo> records = res.getRecords();
        for (MyFollowersVo vo : records) {
            if (!Strings.isEmpty(currentUserId)) {
                UserFollow uesrFollow = userFollowMapper.isFollowed(currentUserId, vo.getUserId());
                vo.setIsFollowed(uesrFollow != null);
            } else {
                vo.setIsFollowed(false);
            }
        }
        return Result.OK(res);
    }

    /**
     * @auther ljm
     * @create 2025/1/29
     * @describe 获取关注信息
     */
    public UserFollow getFollowedInfo(String userId, String followedUserId, int status) {
        LambdaQueryWrapper<UserFollow> query = new LambdaQueryWrapper<UserFollow>().eq(UserFollow::getUserId, userId)
                .eq(UserFollow::getFollowedUserId, followedUserId)
                .eq(UserFollow::getStatus, status);
        return userFollowMapper.selectOne(query);
    }

    /**
     * @auther ljm
     * @create 2025/1/29
     * @describe 关注用户
     */
    @Override
    public Result<Boolean> followed(FollowedParam param) {
        String userId = BaseContext.getId();
        if (Strings.isEmpty(userId)) {
            return Result.error("用户未登录");
        }
        param.setUserId(userId);
        if (Strings.isEmpty(param.getFollowedUserId())) {
            return Result.error("关注用户失败！");
        }
        if (userId.equals(param.getFollowedUserId())) {
            return Result.error("不能关注自己！");
        }
        UserFollow followedInfo = getFollowedInfo(userId, param.getFollowedUserId(), 1);
        if (followedInfo != null) {
            return Result.error("已关注该用户");
        }
        followedInfo = getFollowedInfo(userId, param.getFollowedUserId(), 0);
        // 检查是否是互关
        UserFollow isFollowedInfo = getFollowedInfo(param.getFollowedUserId(), userId, 1);
        boolean isFollowed = false;
        // 更新被关注用户信息
        if (isFollowedInfo != null) {
            isFollowed = true;
            isFollowedInfo.setIsFollowed(isFollowed);
            userFollowMapper.updateById(isFollowedInfo);
        }

        // 更新或插入关注信息
        if (followedInfo != null) {
            followedInfo.setStatus(1);
            followedInfo.setIsFollowed(isFollowed);
            userFollowMapper.updateById(followedInfo);
        } else {
            UserFollow userFollow = new UserFollow();
            BeanUtils.copyProperties(param, userFollow);
            userFollow.setIsFollowed(isFollowed);
            userFollowMapper.insert(userFollow);

        }

        // 更新粉丝总数和关注总数
        fansAdd(param.getFollowedUserId());
        followAdd(userId);
        return Result.OK(true);
    }

    /**
     * @auther ljm
     * @create 2025/1/29
     * @describe 取消关注用户
     */
    @Override
    public Result<Boolean> cancelFollow(CancelFollowParam param) {
        String userId = BaseContext.getId();
        if (Strings.isEmpty(userId)) {
            return Result.error("用户未登录");
        }
        param.setUserId(userId);
        if (Strings.isEmpty(param.getFollowedUserId())) {
            return Result.error("取消关注用户失败！");
        }
        UserFollow followedInfo = getFollowedInfo(userId, param.getFollowedUserId(), 1);
        if (followedInfo == null) {
            return Result.error("尚未关注该用户");
        }
        // 如果是互关的则设为未互关
        if (followedInfo.getIsFollowed()) {
            followedInfo.setIsFollowed(false);
            UserFollow isFollowedInfo = getFollowedInfo(param.getFollowedUserId(), userId, 1);
            if (isFollowedInfo != null) {
                isFollowedInfo.setIsFollowed(false);
                userFollowMapper.updateById(isFollowedInfo);
            }
        }
        followedInfo.setStatus(0);
        userFollowMapper.updateById(followedInfo);

        // 更新粉丝总数和关注总数
        fansSub(param.getFollowedUserId());
        followSub(userId);
        return Result.OK(true);
    }

    /**
     * @auther ljm
     * @create 2025/2/8
     * @describe 粉丝数加1
     */
    void fansAdd(String userId) {
        User user = userMapper.selectById(userId);
        int fansCount = user.getFanCount();
        fansCount++;
        user.setFanCount(fansCount);
        userMapper.updateById(user);
    }

    /**
     * @auther ljm
     * @create 2025/2/8
     * @describe 粉丝数减1
     */
    void fansSub(String userId) {
        User user = userMapper.selectById(userId);
        int fansCount = user.getFanCount();
        if (fansCount > 0) {
            fansCount--;
            user.setFanCount(fansCount);
        }
        userMapper.updateById(user);
    }

    /**
     * @auther ljm
     * @create 2025/2/8
     * @describe 关注数加1
     */
    void followAdd(String userId) {
        User user = userMapper.selectById(userId);
        int followCount = user.getFollowCount();
        followCount++;
        user.setFollowCount(followCount);
        userMapper.updateById(user);
    }

    /**
     * @auther ljm
     * @create 2025/2/8
     * @describe 关注数减1
     */
    void followSub(String userId) {
        User user = userMapper.selectById(userId);
        int followCount = user.getFollowCount();
        if (followCount > 0) {
            followCount--;
            user.setFollowCount(followCount);
        }
        userMapper.updateById(user);
    }
}




